﻿using System.Web.Mvc;
using PhotoAlbums.Models;
using System.Linq;
using System.Data.Entity;
using System;
using System.Net;

namespace PhotoAlbums.Controllers
{
    public class CommentController : Controller
    {
        private PhotoAlbumsDB db = new PhotoAlbumsDB();

        // GET: Comment
        public ActionResult Index(int? photoId)
        {
            // 未登录跳转
            if (Session["id"] == null)
            {
                return RedirectToAction("Login", "User");
            }

            // 判断参数
            if (photoId == null)
            {
                return RedirectToAction("Error", "Home", new { msg = "请求参数丢失" });
            }

            var comment = db.Comment.Include(c => c.User).Where(c => c.PhotoId == photoId);

            // 获取图片
            Photo photo = db.Photo.Find(photoId);

            ViewBag.Photo = photo;
            ViewBag.UserId = (int)Session["id"];

            return View(comment.ToList());
        }

        // GET: Comment/Add
        public ActionResult Add(int? photoId)
        {
            // 未登录跳转
            if (Session["id"] == null)
            {
                return RedirectToAction("Login", "User");
            }

            // 判断参数
            if (photoId == null)
            {
                return RedirectToAction("Error", "Home", new { msg = "请求参数丢失" });
            }

            ViewBag.UserId = new SelectList(db.User, "Id", "Username");
            ViewBag.PhotoId = photoId;
            return View();
        }

        // POST: Comment/Add
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Add([Bind(Include = "Id,UserId,PhotoId,Content,CreateTime")] Comment comment)
        {
            if (ModelState.IsValid)
            {
                // 数据打包：添加创建者、创建时间
                comment.UserId = (int)Session["id"];
                comment.CreateTime = DateTime.Now;

                // 保存数据
                db.Comment.Add(comment);
                db.SaveChanges();
                return RedirectToAction("Index", new { photoId = comment.PhotoId});
            }

            ViewBag.UserId = new SelectList(db.User, "Id", "Username", comment.UserId);
            return View(comment);
        }

        // GET: Comment/Delete/5
        public ActionResult Delete(int id)
        {
            // 未登录跳转
            if (Session["id"] == null)
            {
                return RedirectToAction("Login", "User");
            }

            Comment comment = db.Comment.Find(id);
            db.Comment.Remove(comment);
            db.SaveChanges();
            return RedirectToAction("Index", new { photoId = comment.PhotoId });
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
